package juc.day01;

import java.util.concurrent.CountDownLatch;

/*
CountDownLatch：闭锁，在完成某些运算时，只有其他所有线程的运算全部完成，当前运算才能继续进行
 */
public class TestCountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(5);
        LatchDemo latchDemo = new LatchDemo(latch);
        long start = System.currentTimeMillis();//Type
        for (int i = 0; i < 10; i++) {
            new Thread(latchDemo).start();
        }
        long end = System.currentTimeMillis();
        latch.await();
        System.out.println("耗费实际为:" + (end - start));
    }
}


class LatchDemo implements Runnable {
    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {

        synchronized (this) {
            try {
                for (int i = 2; i < 50000; i = i + 2) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i);
                }
            } finally {
                latch.countDown();
            }
        }


    }
}